package cn.com.dcsgo.listener;

import cn.com.dcsgo.constant.MqConstant;
import cn.com.dcsgo.domain.Order;
import cn.com.dcsgo.dto.StockUpdateDTO;
import cn.com.dcsgo.enums.OrderStatus;
import cn.com.dcsgo.exception.BusinessException;
import cn.com.dcsgo.service.OrderService;
import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.stereotype.Component;

/**
 * 订单延时消息监听者
 *
 * @author Dcsgo
 * @since 2025/11/19 9:59
 */
@Slf4j
@Component
@RocketMQMessageListener(
        topic = MqConstant.ORDER_MS_TOPIC,
        consumerGroup = MqConstant.ORDER_MS_CONSUMER_GROUP,
        namespace = MqConstant.MQ_NAME_SPACE
)
public class OrderMsListener implements RocketMQListener<MessageExt> {
    @Resource
    private OrderService orderService;

    @Override
    public void onMessage(MessageExt messageExt) {
        String orderNumber = messageExt.getKeys();
        log.info("接收到消息：{}", orderNumber);
        //TODO: 这里使用 select IsPayed 会出错，结果集拿不到isPayed会报空指针
        Order order = orderService.getOne(
                new LambdaQueryWrapper<Order>()
                        .select(Order::getOrderId,Order::getStatus)
                        .eq(Order::getOrderNumber, orderNumber)
        );
        log.debug("order:{}", JSON.toJSONString(order));
        if (order == null) {
            log.error("回滚订单失败，失败原因：订单号{}不存在", orderNumber);
            return;
        }
        // 订单状态不为待付款不用回滚
        if (!(order.getStatus() == OrderStatus.PENDING_PAYMENT.getCode())) {
            return;
        }
        StockUpdateDTO stockUpdateDTO = JSON.parseObject(new String(messageExt.getBody()), StockUpdateDTO.class);
        boolean ok = orderService.rollBackOrder(order, stockUpdateDTO);
        if (!ok) {
            throw new BusinessException("订单回滚失败");
        }
    }
}
